<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/inc/core/env.inc.php';

$return["success"] = false;
$return["html"] = null;
$return["jscript"] = null;
$return["error"] = null;

if ($_USER->asPermission('mod_user') || $_USER->get("id") == $_POST["id"]) {
	//fields controll
	$frmFields = new Fields();
	$frmFields->addFiels("old-pass", "string", $_POST["old-pass"]);
	$frmFields->addFiels("new-pass", "string", $_POST["new-pass"]);
	$frmFields->addFiels("repeat-pass", "string", $_POST["repeat-pass"]);
	
	if ($frmFields->isValid() && $_POST["new-pass"] == $_POST["repeat-pass"]) {	
		$return["success"] = $_USER->changePwd($_POST["id"], $_POST["old-pass"], $_POST["new-pass"]);
		$return["jscript"] = 'alert("Password changed");';
		$return["jscript"] .= 'loadSetUser('.$_POST["id"].');';
		
		//send email
		$userMail = new User($_POST["nick"], $_POST["new-pass"]);
		$body = file_get_contents($_SITE['path']['dir']['blocks']['containers']['email'].'/email-ins-user.tag.html');
		$body = str_replace($_TAGS["e-in-name-surname"], $userMail->get("name").' '.$userMail->get("surname"), $body);
		$body = str_replace($_TAGS["e-in-u-nick"], $userMail->get("nick"), $body);
		$body = str_replace($_TAGS["e-in-u-pass"], $_POST["new-pass"], $body);
		
		$domainLevel2 = str_replace("www.", "", $_SITE["domain"]);
		$body = str_replace($_TAGS["e-domain"], $domainLevel2, $body);
			
		$mail = new Mail($userMail->get("email"), $userMail->get("nick"), 'no-reply@'.$domainLevel2, 'Dati account '.$domainLevel2, $body);
			
		if(!$mail->send()) {
			$log = new Log('User.php', 'setPassword.php', 'email not send, change pass, user dettails: '.$userMail->get("nick").' pass: '.$_POST["new-pass"]);
			$log->insert();
		}
	} 
	
	if (!$return["success"]) {
		$return["error"] = 'Error password not change.';
	}
	
	
} else {
	$return["error"] = 'Error not have permission.';
}


echo '('.json_encode($return).')';
?>